package com.lmk.mkcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.lmk.mkcc.domain.CourseMarket;
import com.lmk.mkcc.domain.CourseUserLearn;
import com.lmk.mkcc.dto.PayextparamsDto;
import com.lmk.mkcc.enums.GlobalErrorCode;
import com.lmk.mkcc.mapper.CourseUserLearnMapper;
import com.lmk.mkcc.service.ICourseMarketService;
import com.lmk.mkcc.service.ICourseUserLearnService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lmk.mkcc.util.AssertUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kun
 * @since 2022-09-30
 */
@Service
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {
    @Autowired
    private ICourseMarketService courseMarketService;

    @Override
    public CourseUserLearn getByCourseIdAndLoginId(Long courseId, Long loginId) {
        Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("login_id", loginId);
        wrapper.eq("course_id", courseId);
        return selectOne(wrapper);
    }

    @Override
    public void addPayextparamsDto(PayextparamsDto payextparamsDto) {
        // 参数获取
        String courseIds = payextparamsDto.getCourseIds();
        AssertUtil.isNotNull(courseIds, GlobalErrorCode.DATA_NULL_ERROR);
        String orderNo = payextparamsDto.getOrderNo();
        AssertUtil.isNotNull(orderNo, GlobalErrorCode.DATA_NULL_ERROR);
        Long userId = payextparamsDto.getUserId();
        AssertUtil.isNotNull(userId, GlobalErrorCode.DATA_NULL_ERROR);
        // 根据userid查询该用户是否购买过
        EntityWrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("login_id",userId);
        List<CourseUserLearn> courseUserLearns = selectList(wrapper);
        // 1.对courseid进行分割
        String[] ids = courseIds.split(",");
        // 2.以流的方式将string类型转化为list集合
        List<Long> collect = Arrays.stream(ids).map(id -> Long.valueOf(id)).collect(Collectors.toList());
        // 3.定义一个空的map
        Map<Long,CourseUserLearn> courseUserLearnMap=null;
        if (courseUserLearns!=null&&courseUserLearns.size()>0){// 用户之前购买过课程
            // 使用courseUserLearnMap来装载参数，key是courseId，value为courseuserlearn对象
            courseUserLearnMap=courseUserLearns.stream().collect(Collectors.toMap(CourseUserLearn::getCourseId,courseUserLearn -> courseUserLearn));
        }else {// 用户没购买过
            courseUserLearnMap = new HashMap<>();

        }

        List<CourseMarket> courseMarkets = courseMarketService.selectBatchIds(collect);
        Map<Long, CourseMarket> courseMarketMap = courseMarkets.stream().collect(Collectors.toMap(CourseMarket::getId, courseMarket -> courseMarket));

        for (Long courseId : collect) {
            CourseUserLearn courseUserLearn = courseUserLearnMap.get(courseId);
            CourseMarket courseMarket = courseMarketMap.get(courseId);
            Integer validDays = courseMarket.getValidDays();

            if (courseUserLearn==null){// 如果用户是第一次购买
                CourseUserLearn courseUserLearn1 = new CourseUserLearn();
                courseUserLearn1.setLoginId(userId);
                courseUserLearn1.setStartTime(new Date());
                courseUserLearn1.setEndTime(DateUtils.addDays(new Date(),validDays));
                courseUserLearn1.setState(0);// 0是已购买，1是已过期
                courseUserLearn1.setCourseId(courseId);
                courseUserLearn1.setCourseOrderNo(orderNo);
                courseUserLearn1.setCreateTime(new Date());
                insert(courseUserLearn1);
            }else {// 用户曾经买过课
                if (courseUserLearn.getState()==0){// 用户买了而且没有过期
                    Date endTime = courseUserLearn.getEndTime();
                    courseUserLearn.setStartTime(new Date());
                    courseUserLearn.setEndTime(DateUtils.addDays(endTime,validDays));
                }else {// 用户买过而且过期了
                    courseUserLearn.setState(0);
                    courseUserLearn.setStartTime(new Date());
                    courseUserLearn.setEndTime(DateUtils.addDays(new Date(),validDays));
                    courseUserLearn.setCourseOrderNo(orderNo);
                    courseUserLearn.setCreateTime(new Date());
                }
                updateById(courseUserLearn);
            }
        }



    }
}
